import { apiurl,zwapploginurl,alipayloginurl } from '@/common/config.js'
import common from '@/utils/common'
import store from '@/utils/store'
let App = app;

export default function api(param, noToast) {
	
	let url = param.url || '';
	let data = param.data || {};
	let method = param.method || 'GET';
	let promise = ''; //
	method = method.toUpperCase();
	if (url) {
		if (url.split('/').length == 2) {
			url = 'api/' + url;
		}
	}
	url = apiurl() + url;

	noToast ? '' : uni.showLoading({
		title: '加载中...',
	})

	/**
	 * code 返回的code值
	 * 1=成功 处理结果
	 * 2=成功 关闭当前页面，跳转到应用内的某个页面 param=参数
	 * 401=需要登录处理
	 * -1 = 错误处理
	 */
	return new Promise((resolve, reject) => {
		data.authToken = uni.getStorageSync('user_info').token || '';
		uni.request({
			url: url,
			method,
			data,
			header: {
			     // 'content-type':'application/json',
				 'content-type':'application/x-www-form-urlencoded'
				// "authToken": uni.getStorageSync('user_info').token || '',
				// 'appid':uni.getAccountInfoSync().miniProgram.appId
			},

			complete(respone) {
				
				if (!respone) {
					uni.hideLoading();
					reject('返回值已被您拦截！');
					return;
				} else {
					let app_type = uni.getStorageSync('app_type');
					let res = respone.data;
					// console.log('complete——res',res)
					switch (res.code) {
						case 1:
							uni.hideLoading();
							resolve(res.data);
							break;
						case 2:
							uni.hideLoading();
							uni.redirectTo({
								url: 'success' + res.data.param
							})
							break;
						case 401:
							let page = common.getPageUrl();
							if(uni.getStorageSync('app_type')=='h5'){
								uni.showModal({
									title: '提示',
									content: '请登录后操作~',
									success(e) {
										// uni.setStorageSync('page', page)
										if(e.confirm){
											uni.redirectTo({
												url: '/pages/login/index'
											})
										}
									}
								})
							}
							break;
						default:
							// uni.showModal({
							// 	title: '提示',
							// 	content: res
							// })
							reject(respone);
							break;
					}
				}
			}
		});
		uni.hideLoading();
		uni.stopPullDownRefresh();
	}).catch(err => {
		uni.showModal({
			title: '提示',
			content: err.data.msg
		})
		// console.log(err)
	})

}